package smecta.client.print.controller;

import javafx.fxml.FXML;
import javafx.print.Printer;
import javafx.print.PrinterJob;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.Stage;
import javafx.collections.ObservableList;
import javafx.scene.control.TableView;
import javafx.scene.control.TableColumn;
import javafx.concurrent.Worker;
import smecta.client.print.util.RowData;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


import java.io.FileInputStream;
import java.io.IOException;
import java.time.LocalDateTime;

public class PrintPreviewViewController {

    @FXML
    private WebView webView;
    @FXML
    private TableView<RowData> dataTableView;

    public void setDataTableView(TableView<RowData> dataTableView) {
        this.dataTableView = dataTableView;
    }

    private Properties printSettings;
    private List<String> allPagesContent;
    private int currentPageIndex;

    @FXML
    public void initialize() {
        // 初始化逻辑
//        loadPrintSettings();

    }
    public void initialize_later() {
        // 加载打印设置
        loadPrintSettings();
        // 生成并显示打印预览内容
        generatePreviewContent();
        showPage(0);
    }
    private void loadPrintSettings() {
        printSettings = new Properties();
        try (FileInputStream input = new FileInputStream("./samplePanel.ini")) {
            printSettings.load(input);
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    private void generatePreviewContent() {
        allPagesContent = new ArrayList<>();
        ObservableList<RowData> selectedItems = dataTableView.getSelectionModel().getSelectedItems();

        int labelWidth = Integer.parseInt(printSettings.getProperty("labelWidth", "200"));
        int labelHeight = Integer.parseInt(printSettings.getProperty("labelHeight", "100"));
        int labelColumns = Integer.parseInt(printSettings.getProperty("labelColumns", "1"));

        int columnWidth = labelWidth / labelColumns;
        int currentLabelCount = 0;

        for (RowData rowData : selectedItems) {
            int startSpindle = Integer.parseInt(rowData.getCellValue("Title6").get());
            int endSpindle = Integer.parseInt(rowData.getCellValue("Title7").get());

            int totalItem=endSpindle - startSpindle + 1;
            int totalLabels = totalItem / labelColumns;
            if (totalItem % labelColumns != 0) {
                totalLabels += 1;
            }

            for (int i = 0; i < totalLabels; i++) {
                StringBuilder htmlContent = new StringBuilder("<html><body>");
                htmlContent.append("<div style='border: 1px solid black; margin-bottom: 10px; padding: 10px; position: relative; width: ")
                        .append(labelWidth)
                        .append("px; height: ")
                        .append(labelHeight)
                        .append("px;'>");

                for(int l=0;l<labelColumns;l++)
                {
                    int currentSpindle = startSpindle + i * labelColumns;
                    for (int j = 0; j < labelColumns && currentSpindle + j <= endSpindle; j++) {
                        int left = j * columnWidth;
                        htmlContent.append("<div style='position: absolute; left: ")
                                .append(left)
                                .append("px; top: 0; width: ")
                                .append(columnWidth)
                                .append("px; height: ")
                                .append(labelHeight)
                                .append("px;'>");

                        for (TableColumn<RowData, ?> column : dataTableView.getColumns()) {
                            String columnId = column.getId();
                            String columnValue = rowData.getCellValue(columnId) == null ? "" : rowData.getCellValue(columnId).get();

                            if (printSettings.getProperty(columnId + ".printable", "false").equals("true")) {
                                if (columnId.equals("Title6")) {
                                    htmlContent.append(createHtmlForTitle(columnId, String.valueOf(currentSpindle + j)));
                                } else {
                                    htmlContent.append(createHtmlForTitle(columnId, columnValue));
                                }
                            }
                        }
                        htmlContent.append("</div>");
                    }

                    currentLabelCount++;
                    if(currentLabelCount>=totalItem&&currentLabelCount%labelColumns!=0)
                    {
                        break;
                    }
                }
                htmlContent.append("</div></body></html>");
                allPagesContent.add(htmlContent.toString());
            }

        }


    }

    private String createHtmlForTitle(String columnId, String value) {
        String left = printSettings.getProperty(columnId + ".x", "0");
        String top = printSettings.getProperty(columnId + ".y", "0");
        String fontSize = printSettings.getProperty(columnId + ".fontSize", "12");

        return "<div style='position: absolute; left: " + left + "px; top: " + top + "px; font-size: " + fontSize + "px;'>" + value + "</div>";
    }

    private void showPage(int pageIndex) {
        if (pageIndex >= 0 && pageIndex < allPagesContent.size()) {
            currentPageIndex = pageIndex;
            WebEngine webEngine = webView.getEngine();
            String pageContent = allPagesContent.get(pageIndex);
            webEngine.loadContent(pageContent);
        }
    }

    @FXML
    private void handleFirstPage() {
        showPage(0);
    }

    @FXML
    private void handlePreviousPage() {
        System.out.println("handlePreviousPage:"+currentPageIndex);
        if (currentPageIndex > 0) {
            showPage(currentPageIndex - 1);
        }
    }

    @FXML
    private void handleNextPage() {
        System.out.println("currentPageIndex:"+currentPageIndex+" allPagesContent:"+allPagesContent.size());
        if (currentPageIndex < allPagesContent.size() - 1) {
            showPage(currentPageIndex + 1);
        }
    }

    @FXML
    private void handleLastPage() {
        showPage(allPagesContent.size() - 1);
    }

    @FXML
    private void handleZoomIn() {
        webView.setZoom(webView.getZoom() + 0.1);
    }

    @FXML
    private void handleZoomOut() {
        webView.setZoom(webView.getZoom() - 0.1);
    }

    @FXML
    private void handlePrint() {
        // 获取默认打印机名称
        String defaultPrinterName = printSettings.getProperty("printerSelection", "");
        Printer defaultPrinter = null;

        if (!defaultPrinterName.isEmpty()) {
            System.out.println("defaultPrinterName:" + defaultPrinterName);
            defaultPrinter = Printer.getAllPrinters().stream()
                    .filter(printer -> printer.getName().equals(defaultPrinterName))
                    .findFirst()
                    .orElse(null);
            System.out.println("defaultPrinter:" + defaultPrinter);
        }

        for (String pageContent : allPagesContent) {
            PrinterJob printerJob = PrinterJob.createPrinterJob();
            WebView webView=new WebView();
            if (printerJob == null) {
                System.out.println("No printers are available.");
                continue;
            }

            if (defaultPrinter != null) {
                printerJob.setPrinter(defaultPrinter);
            }

            WebEngine webEngine = webView.getEngine();
            webEngine.loadContent(pageContent);


            webEngine.getLoadWorker().stateProperty().addListener((obs, oldState, newState) -> {
                if (newState == Worker.State.SUCCEEDED) {
                    // Print the loaded content
                    if (printerJob.printPage(webView)) {
                        printerJob.endJob();
                        System.out.println("Printed page"+LocalDateTime.now());
                    } else {
                        System.out.println("Failed to print page"+LocalDateTime.now());
                    }
                }
            });
            try {
                // Give some time for the content to load and render
                Thread.sleep(1000); // You can adjust the sleep time if needed
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @FXML
    private void handleClose() {
        Stage stage = (Stage) webView.getScene().getWindow();
        stage.close();
    }

}
